package com.dataseek.iot.core.util;

import com.dataseek.iot.core.jwt.JwtTokenProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

/**
 * @author cc
 * @Title: 权限工具类
 * @Description: 权限工具类
 * @date 2021/10/258:33 上午
 * @since 1.0
 */
@Component
@Slf4j
public class AuthUtil {


    /**
     * 获取用户名称
     * @param exchange
     * @param jwtTokenProvider
     * @return
     */
    public static String getUsername(ServerWebExchange exchange, JwtTokenProvider jwtTokenProvider){
        Authentication auth =getAuth(exchange, jwtTokenProvider);
        org.springframework.security.core.userdetails.User principal = (org.springframework.security.core.userdetails.User) auth.getPrincipal();
        return principal.getUsername();
    }

    /**
     * 获取权限信息
     * @param exchange
     * @param jwtTokenProvider
     * @return
     */
    public static Authentication getAuth(ServerWebExchange exchange, JwtTokenProvider jwtTokenProvider){
        String bearerToken = exchange.getRequest().getHeaders().get("Authorization").get(0);
        log.info("权限信息为："+bearerToken);
        String token = null;
        String[] params = bearerToken.split(" ");
        if(params.length==3){
            token = params[2];
        }
        if(params.length==2){
            token  = params[1];
        }
        Authentication authentication = jwtTokenProvider.getAuthentication(token);
        return authentication;
    }


}
